<template>
  <view class="page">
    <view class="card">
      <text class="title">编辑资料</text>
      <image class="avatar" :src="form.avatar || defaultAvatar" mode="aspectFill" @click="chooseAvatar" />
      <button class="upload-btn" @click="chooseAvatar">选择头像</button>
      <input class="ipt" placeholder="昵称" v-model="form.nickname" />
      <button class="btn" @click="save">保存</button>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'

const API_BASE_URL = 'http://localhost:3001'
const defaultAvatar = 'https://ai-public.mastergo.com/ai/img_res/4f8c61af426b6e29d3c0f5ce2f9e1f66.jpg'
const userId = ref('0')
const form = ref({ nickname: '', avatar: '' })

const fetchProfile = async () => {
  const id = userId.value
  try {
    const res = await uni.request({ url: `${API_BASE_URL}/api/users/${id}`, method: 'GET' })
    const u = res?.data as any
    form.value = { nickname: u?.nickname || '', avatar: u?.avatar || '' }
  } catch {}
}

const chooseAvatar = () => {
  // 显示选择方式
  uni.showActionSheet({
    itemList: ['从相册选择', '使用默认头像'],
    success: (res) => {
      if (res.tapIndex === 0) {
        // 从相册选择
        uni.chooseImage({
          count: 1,
          sizeType: ['compressed'],
          sourceType: ['album'],
          success: (res) => {
            const tempFilePath = res.tempFilePaths[0]
            form.value.avatar = tempFilePath
            uni.showToast({ title: '头像已选择', icon: 'success' })
          },
          fail: () => {
            uni.showToast({ title: '选择失败', icon: 'none' })
          }
        })
      } else if (res.tapIndex === 1) {
        // 使用默认头像
        form.value.avatar = defaultAvatar
        uni.showToast({ title: '已使用默认头像', icon: 'success' })
      }
    }
  })
}

const save = async () => {
  try {
    await uni.request({
      url: `${API_BASE_URL}/api/users/${userId.value}`,
      method: 'PUT',
      data: { nickname: form.value.nickname, avatar: form.value.avatar },
      header: { 'content-type': 'application/json' }
    })
    // 更新本地存储的用户信息
    const localUser = uni.getStorageSync('user') || {}
    const newUser = { 
      ...localUser, 
      nickname: form.value.nickname || localUser.nickname, 
      avatar: form.value.avatar || localUser.avatar 
    }
    uni.setStorageSync('user', newUser)
    uni.showToast({ title: '已保存', icon: 'success' })
    setTimeout(() => uni.navigateBack(), 400)
  } catch {
    uni.showToast({ title: '保存失败', icon: 'none' })
  }
}

onLoad(() => {
  const localUser = uni.getStorageSync('user')
  if (!localUser?.id) return uni.redirectTo({ url: '/pages/auth/login' })
  userId.value = String(localUser.id)
  fetchProfile()
})
</script>

<style>
.page { min-height: 100vh; background: #f7f8fa; display: flex; justify-content: center; align-items: flex-start; }
.card { width: 86%; margin-top: 40rpx; background: #fff; border-radius: 16rpx; padding: 30rpx; box-shadow: 0 6rpx 24rpx rgba(0,0,0,0.06); }
.title { font-size: 34rpx; color: #333; font-weight: 600; margin-bottom: 20rpx; display: block; }
.avatar { width: 140rpx; height: 140rpx; border-radius: 70rpx; display: block; margin: 0 auto 20rpx auto; }
.upload-btn { height: 60rpx; background: #f0f0f0; color: #333; border: none; border-radius: 8rpx; margin-bottom: 20rpx; font-size: 24rpx; }
.ipt { height: 86rpx; background: #f5f6f7; border-radius: 12rpx; padding: 0 22rpx; margin-bottom: 20rpx; }
.btn { height: 86rpx; background: #007AFF; color: #fff; border: none; border-radius: 12rpx; }
</style>


